package file.network;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import utils.Configuration;

import file.BadFileTypeException;
import file.TransferFile;
import file.TransferFileObserver;

public class FileSender extends Thread {
	
	InetSocketAddress receiverAddr ;
	TransferFile file ;
	TransferFileObserver[] tfos ;
	
	/**
	 * Create a new FileSender that will send the file specified to
	 * the receiver stored in file (at port) and notify all the observers 
	 * in tfos.
	 * 
	 * @param file The file to send
	 * @param tfos The observer to notify on transfer update
	 * @param port The port to connect
	 */
	public FileSender (TransferFile file, TransferFileObserver[] tfos, int port) {
		this.file = file ;
		this.tfos = tfos ;
		this.receiverAddr = new InetSocketAddress(file.getReceiver().getAddress(), port) ;
	}
	
	public void run () {
		Socket so = new Socket () ;
		try {
			Configuration.file_debug.println("Sending file to : " + this.receiverAddr.getPort()) ;
			so.connect(this.receiverAddr) ;
			this.file.send(so.getOutputStream(), this.tfos) ;
			so.close() ;
		} 
		catch (IOException e) {
			Configuration.file_debug.println("Fail to send file to : " + this.receiverAddr.getPort()) ;
		} 
		catch (BadFileTypeException e) {
			Configuration.file_debug.println("Fail to send file to : " + this.receiverAddr.getPort()) ;
		}
	}
	
}
